"""
    Author:
    Date: 2019-03-08

    微信管理后台-消息广播
"""

from django.shortcuts import render

from entities.consts import *
from entities import user_mgr
from entities import radio_mgr
from utils.log import Log

from .. import helpers
from .. helpers import gma_login_required


@gma_login_required
def index(request):
    """ 首页 """
    context = helpers.build_context(request)

    context['total_user_count'] = user_mgr.get_total_user_count()
    context['total_premium_user_count'] = user_mgr.get_total_premium_user_count()
    context['total_test_user_count'] = user_mgr.get_total_test_user_count()
    context['total_caster_count'] = user_mgr.get_total_broadcaster_count(request=request)
    context['total_online_caster_count'] = user_mgr.get_total_online_broadcaster_count()

    context['radio_log_count'] = radio_mgr.get_total_message_count()
    return render(request, 'gma/radio/radio_home.html', context)


@gma_login_required
def edit_radio_message(request, category, uid=None):
    """ 给指定的用户群体发送消息 """
    category = int(category)
    if uid is None:
        uid = 0

    # 计算发送对象的用户数量
    user_count = 0
    if category == USER_CATEGORY_NONE:
        user_count = 1
    elif category == USER_CATEGORY_ALL_USERS:
        user_count = user_mgr.get_total_user_count()
    elif category == USER_CATEGORY_ALL_PREMIUM_USERS:
        user_count = user_mgr.get_total_premium_user_count()
    elif category == USER_CATEGORY_ALL_CASTERS:
        user_count = user_mgr.get_total_broadcaster_count(request=request)
    elif category == USER_CATEGORY_ALL_ONLINE_CASTERS:
        user_count = user_mgr.get_total_online_broadcaster_count()
    elif category == USER_CATEGORY_TEST_USERS:
        user_count = user_mgr.get_total_test_user_count()
    else:
        Log.error(f'Invalid user category: {category}')
        return helpers.show_page_tips(request, '无效的用户分类！')

    context = helpers.build_context(request)
    context['category'] = category
    context['category_desp'] = get_user_category_desp(category)
    context['uid'] = uid
    context['user_count'] = user_count
    return render(request, 'gma/radio/edit_message.html', context)


@gma_login_required
def radio_message_logs(request):
    """ 显示广播详细的数量 """
    logs = radio_mgr.get_message_logs(100)
    for log in logs:
        log['category_desp'] = get_user_category_desp(log['category'])

    context = helpers.build_context(request)
    context['logs'] = logs
    return render(request, 'gma/radio/message_list.html', context)


if __name__ == '__main__':
    print('ok')
